package com.link.play.fit.ai.ui.vip

import android.annotation.SuppressLint
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Bundle
import android.view.ViewGroup
import android.widget.MediaController
import android.widget.Toast
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.android.billingclient.api.ProductDetails
import com.bumptech.glide.Glide
import com.link.play.fit.ai.BuildConfig
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.AcVipFreeBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.SUB_PRODUCT_TYPE
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.utils.DateEx.getCurrentDayOfMonth
import com.link.play.fit.ai.utils.GooglePayUtil
import com.link.play.fit.ai.utils.ScreenUtil
import com.link.play.fit.ai.utils.TimeUtils.calculateEndDate
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class VipFreeAc : BaseActivity<AcVipFreeBinding>(AcVipFreeBinding::inflate) {
    private var subscriptionOfferDetails: List<ProductDetails.SubscriptionOfferDetails>? = null
    private var productDetails: ProductDetails? = null
    private var isNext = false
    private var formattedPrice = ""
    private var isGuide = false
    private var buyType = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)

        isGuide = intent.extras?.getBoolean("isGuide") ?: false
        buyType = intent.extras?.getString("buyType") ?: ""
        "buyType  $buyType".d()
        observerRequest()
        initListener()
        initVideo()
    }

    @SuppressLint("DefaultLocale")
    private fun initListener() {
        onBackPressedDispatcher.addCallback {
            finish()
            overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right)
        }
        binding.backImg.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvTryFree.setOnClickListener {
            goToAc(VipBuyDesAc::class.java) {
                putExtra("isGuide", isGuide)
            }
            if (RemoteConfig.noVipCanIn) {
                finish()
            }
        }
    }

    private fun initVideo() = with(binding) {
        val params = binding.videoView.layoutParams as ViewGroup.MarginLayoutParams
        params.width = (ScreenUtil.getWidthPixels(this@VipFreeAc) * 0.8).toInt()
        params.height = (ScreenUtil.getWidthPixels(this@VipFreeAc) * 0.8 * 1.77).toInt()
        binding.videoView.layoutParams = params

        val rawUri = Uri.parse("android.resource://${packageName}/${R.raw.video_free}")
        // 2. 异步获取首帧
//        val retriever = MediaMetadataRetriever()
//        retriever.setDataSource(this@VipFreeAc, rawUri)
//        val frame = retriever.frameAtTime
//        binding.videoViewImg.setImageBitmap(frame)
//        binding.videoViewImg.isVisible = true


//        val mediaController = MediaController(this@VipFreeAc)
//        mediaController.setAnchorView(videoView)
//        videoView.setMediaController(mediaController)
//
        videoView.setVideoURI(rawUri)
        videoView.start()
//        videoView.setOnPreparedListener {
//            binding.videoViewImg.isVisible = false
//            it.start()
//        }

        videoView.setOnCompletionListener {
            videoView.seekTo(0)
            videoView.start()
        }
    }

    private fun observerRequest() {

//        lifecycleScope.launch {
//            productDetails = GooglePayUtil.queryProduct(SUB_YEAR_product_ID)
//            subscriptionOfferDetails = productDetails?.subscriptionOfferDetails
//            productDetails?.subscriptionOfferDetails?.forEach {
//                val pricingPhase = it.pricingPhases.pricingPhaseList[0]
//                when (it.basePlanId) {
//                    SUB_YEAR_PLAN_ID -> {
//                        formattedPrice = pricingPhase.formattedPrice
//                        val formattedText = getString(
//                            R.string.just_per_year,
//                            formattedPrice,
//                            extractAndCalculateDailyPriceToMonth(formattedPrice)
//                        )
//                        binding.tvPerYear.text = formattedText
//                        isNext = true
//
//                    }
//
//                    else -> {}
//                }
//
//            }
//        }

    }

    override fun onResume() {
        super.onResume()
//        GooglePayUtil.startConnection()
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "isVip") {
            lifecycleScope.launch {
                val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                userGuide?.apply {
                    if (buyType.isNotEmpty()) {
                        planStartTime = getCurrentDayOfMonth()
                    }
                    "getCurrentDayOfMonth ${getCurrentDayOfMonth()} SUB_PRODUCT_TYPE $SUB_PRODUCT_TYPE".d()
                    subEndTime = calculateEndDate(getCurrentDayOfMonth(), SUB_PRODUCT_TYPE) ?: ""
                    CloudStore.set(DOC_USER_GUIDE, this)
                }
                Toast.makeText(this@VipFreeAc, getString(R.string.subscription_successful), Toast.LENGTH_SHORT)
                    .show()
                "buyType $buyType".d()
                if (!isGuide) {
                    when (buyType) {
                        "controlPlan" -> {
                            EventBus.getDefault().post("flushResult")
                        }

                        "controlFg" -> {
                            EventBus.getDefault().post("flushMain")
                        }

                        else -> {
                            goToAc(MainAc::class.java)
                        }
                    }
                }
                finish()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        binding.videoView.pause()
    }

    override fun onStart() {
        super.onStart()
        binding.videoView.start()

    }

    override fun onDestroy() {
        super.onDestroy()
        binding.videoView.suspend() // 释放资源
        EventBus.getDefault().unregister(this)
    }
}